package com.example.dubbo.demo.server.configurations;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.example.dubbo.demo.server.base.BaseEntity;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * @author dzii
 */
@Configuration
@MapperScan(basePackages = "com.example.dubbo.demo.server.modules.**.mapper")
public class MybatisConfigurations {

    @Bean
    public MybatisPlusInterceptor interceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                if (metaObject.getOriginalObject() instanceof BaseEntity) {
                    strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
                    strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
                    strictInsertFill(metaObject, "createBy", () -> 1L, Long.class);
                }
            }


            @Override
            public void updateFill(MetaObject metaObject) {
                if (metaObject.getOriginalObject() instanceof BaseEntity) {
                    strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
                }
            }
        };
    }

}
